#!/bin/bash

datafile=contact.dat


init() {
    touch "$datafile"
}

getdata() {
    local msg=$1 emptyok=$2
    while true
    do
        read -p "$msg"
        if test -z "$REPLY"; then
            if test "$emptyok" = 1; then
                break
            fi
            echo "can not be empty"
            continue
        fi
        echo "$REPLY"
        break
    done
}

exists() {
    grep -qE "$1" "$datafile"
}

add() {
    # 通过交互式的方式从用户获取联系人信息 (read, echo)
    # 如果记录已经存在，就报错，不要再次添加 （姓名，性别，电话全部相同）
    # 可以用grep 来确认记录是否存在
    # 记录样式：
    #   一个联系人一行记录 （参考格式  张三:男:18612345678）
    name=$(getdata "name: ")
    gender=$(getdata "gender: ")
    phone=$(getdata "phone: ")

    record="$name:$gender:$phone"
    if exists "$record"; then
        echo "record exists, exit" >&2
        return
    fi
    echo "$record" >> "$datafile"
}

delete() {
    # 删除之前把记录输出到屏幕上，等待用户确认
    n=$(search "$1" | wc -l)
    local force=$2

    if test "$n" -gt 1; then
        if test "$force" = 1; then
            sed -i "/${1}/d" "$datafile"
        else
            search "$1"
            read -p "confirm? (y/n) " ans
            if test "$ans" = y; then
                sed -i "/${1}/d" "$datafile"
            fi
        fi
    else
        echo "no match, nothing to delete"
    fi

}

modify() {
    # 修改的时候把字段原有的值作为默认值，提示用户，
    # 如果用户直接按Enter，就是用此默认值
    #     ** read -p "Name[$old_name]: " name
    #     ** test -z "$name" && name=$old_name
    # 决定把改好的记录写入文件之前，先把新记录输出到屏幕，等待用户确认
    #     ** read -p "confirm? (y/n) " ans
    #     ** test "$ans" != y -a "$ans" != Y && exit
    local record name gender phone
    record=$(_search "$@" | head -n1)
    IFS=: read name gender phone <<<"$record"
    new_name=$(getdata "name: [$name] " 1)
    test -z "$new_name" && new_name=$name
    new_gender=$(getdata "gender: [$gender] " 1)
    test -z "$new_gender" && new_gender=$gender
    new_phone=$(getdata "phone: [$phone] " 1)
    test -z "$new_phone" && new_phone=$phone

    # 删除旧记录，不等用户确认
    delete "$1" 1

    # 添加修改后的记录
    record="$new_name:$new_gender:$new_phone"
    echo "$record" >> "$datafile"
}

list() {
    # 能够一次性列出所有的联系人信息 (cat, sed)
    # ** echo '张三:男:18612345678' | sed 's/:/ /g' | column -t
    local header="Name Gender Phone"
    if test $(wc -l < "$datafile") -gt 0; then
        { echo "$header"; sed 's/:/ /g' "$datafile"; } | column -t
    fi
}

_search() {
    grep -E "$1" "$datafile"
}

search() {
    # 能够查询符合某些信息的联系人 （姓名，性别，电话）
    # ** grep 张三 contact.dat
    local header="Name Gender Phone"
    { echo "$header"; _search "$1" | sed 's/:/ /g'; } | column -t
}


# 脚本从这里真正开始

# 初始化环境
init

cmd=$1
shift

case "$cmd" in
    add)
        add;;
    del)
        delete "$@";;
    mod)
        modify "$@";;
    list)
        list;;
    search)
        search "$@";;
    *)
        echo "$cmd not supported" >&2
        echo "usage: $(basename $0) add|del|mod|list|search [argument]..." >&2
        exit 1
esac
